<template>
  <!-- 搜索触发按钮 -->
  <div class="search-trigger" @click="openSearch">
    <a-input
      placeholder="搜索题目、文章、好友..."
      :value="''"
      readonly
      class="search-input-trigger"
      suffix-icon="search"
    >
      <template #suffix>
        <SearchOutlined />
      </template>
    </a-input>
  </div>

  <!-- 搜索弹窗 -->
  <a-modal
    v-model:open="searchVisible"
    :footer="null"
    :closable="false"
    :width="1000"
    :body-style="{ height: '80vh', padding: 0 }"
    :centered="true"
    class="search-modal"
  >
    <div class="search-dialog">
      <!-- 搜索输入区域 -->
      <div class="search-input-section">
        <div class="search-input-wrapper">
          <SearchOutlined class="search-input-icon" />
          <a-input
            ref="searchInputRef"
            v-model:value="searchQuery"
            placeholder="搜索题目、文章、好友..."
            class="search-main-input"
            size="large"

            @keydown="handleKeydown"
            @keyup="handleKeyup"
            @compositionstart="handleCompositionStart"
            @compositionend="handleCompositionEnd"
          />
          <CloseOutlined class="search-close-btn" @click="closeSearch" />
        </div>
      </div>
      
      <!-- 选项卡区域 -->
      <div class="search-tabs-section">
        <a-tabs
          v-model:activeKey="activeTab"
          @change="onTabChange"
          class="search-main-tabs"
          size="large"
        >
          <a-tab-pane key="problems" tab="题目">
            <div class="search-results">
              <div v-if="loading" class="loading-container">
                <a-spin size="large" />
              </div>
              <div v-else-if="searchResults.problems.length === 0 && hasSearched" class="no-results">
                <EmptyIcon class="empty-icon" />
                <p>未找到相关题目</p>
              </div>
              <div v-else-if="searchResults.problems.length > 0" class="results-list">
                <ProblemList :problems="searchResults.problems" :show-pagination="false" />
              </div>
              <div v-else class="search-tips">
                <p>输入关键词搜索题目</p>
              </div>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="blogs" tab="文章">
            <div class="search-results">
              <div v-if="loading" class="loading-container">
                <a-spin size="large" />
              </div>
              <div v-else-if="searchResults.blogs.length === 0 && hasSearched" class="no-results">
                <EmptyIcon class="empty-icon" />
                <p>未找到相关文章</p>
              </div>
              <div v-else-if="searchResults.blogs.length > 0" class="results-list">
                <BlogList :blogs="searchResults.blogs" :show-pagination="false" />
              </div>
              <div v-else class="search-tips">
                <p>输入关键词搜索文章</p>
              </div>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="users" tab="好友">
            <div class="search-results">
              <div v-if="loading" class="loading-container">
                <a-spin size="large" />
              </div>
              <div v-else-if="searchResults.users.length === 0 && hasSearched" class="no-results">
                <EmptyIcon class="empty-icon" />
                <p>未找到相关用户</p>
              </div>
              <div v-else-if="searchResults.users.length > 0" class="results-list">
                <FriendListWithFollow :friends="searchResults.users" :show-pagination="false" />
              </div>
              <div v-else class="search-tips">
                <p>输入关键词搜索好友</p>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { ref, reactive, watch, nextTick, onMounted, h } from 'vue'
import { useRoute } from 'vue-router'
import { SearchOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { searchContent } from '@/api/home'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import ProblemList from './ProblemList.vue'
import BlogList from './BlogList.vue'
import FriendListWithFollow from './FriendListWithFollow.vue'

// 空状态图标组件
const EmptyIcon = {
  render() {
    return h('svg', {
      width: '64',
      height: '64',
      viewBox: '0 0 64 64',
      fill: 'none',
      xmlns: 'http://www.w3.org/2000/svg'
    }, [
      h('circle', {
        cx: '32',
        cy: '32',
        r: '30',
        stroke: '#d9d9d9',
        'stroke-width': '2',
        fill: 'none'
      }),
      h('path', {
        d: 'M32 20v24M20 32h24',
        stroke: '#d9d9d9',
        'stroke-width': '2',
        'stroke-linecap': 'round'
      })
    ])
  }
}

export default {
  name: 'GlobalSearch',
  components: {
    SearchOutlined,
    CloseOutlined,
    ProblemList,
    BlogList,
    FriendListWithFollow,
    EmptyIcon
  },
  setup() {
    const route = useRoute()
    const userStore = useUserStore()
    const { userStats } = storeToRefs(userStore)
    
    const searchVisible = ref(false)
    const searchQuery = ref('')
    const activeTab = ref('problems')
    const loading = ref(false)
    const hasSearched = ref(false)
    const searchInputRef = ref(null)
    
    const searchResults = reactive({
      problems: [],
      blogs: [],
      users: [],
      total: 0
    })
    
    // 根据当前路由设置默认选项卡
    const setDefaultTab = () => {
      const path = route.path
      if (path.includes('/blog')) {
        activeTab.value = 'blogs'
      } else if (path.includes('/chat')) {
        activeTab.value = 'users'
      } else {
        activeTab.value = 'problems'
      }
    }
    
    // 打开搜索
    const openSearch = () => {
      setDefaultTab()
      searchVisible.value = true
      nextTick(() => {
        searchInputRef.value?.focus()
      })
    }
    
    // 关闭搜索
    const closeSearch = () => {
      searchVisible.value = false
      searchQuery.value = ''
      hasSearched.value = false
      // 清空搜索结果
      searchResults.problems = []
      searchResults.blogs = []
      searchResults.users = []
      searchResults.total = 0
    }
    
    // 清空搜索结果
    const clearSearchResults = () => {
      hasSearched.value = false
      searchResults.problems = []
      searchResults.blogs = []
      searchResults.users = []
      searchResults.total = 0
    }
    
    // 选项卡切换
    const onTabChange = (key) => {
      activeTab.value = key
      if (searchQuery.value.trim()) {
        clearSearchResults()
      }
    }
    
    // 中文输入法状态
    const isComposing = ref(false)
    
    // 处理中文输入法开始
    const handleCompositionStart = () => {
      isComposing.value = true
    }
    
    // 处理中文输入法结束
    const handleCompositionEnd = (event) => {
      isComposing.value = false
      // 如果输入法结束时按下的是回车键，延迟一下再处理
      if (event.data && searchQuery.value.trim()) {
        setTimeout(() => {
          // 这里不自动触发搜索，让用户再次按回车
        }, 0)
      }
    }
    
    // 处理键盘按下事件
    const handleKeydown = (event) => {
      if (event.key === 'Escape') {
        closeSearch()
      }
    }
    
    // 处理键盘释放事件
    const handleKeyup = (event) => {
      if (event.key === 'Enter' && !isComposing.value) {
        performSearch()
      }
    }
    
    // 执行搜索
    const performSearch = async () => {
      if (!searchQuery.value.trim()) return
      
      loading.value = true
      hasSearched.value = true
      
      try {
        const response = await searchContent({
          token: userStats.value.token || '',
          query: searchQuery.value.trim(),
          type: activeTab.value,
          page: 1,
          page_size: 20
        })
        
        if (response.success) {
          // 清空所有结果
          searchResults.problems = []
          searchResults.blogs = []
          searchResults.users = []
          
          // 根据搜索类型设置结果
          if (activeTab.value === 'problems') {
            searchResults.problems = response.problems || []
          } else if (activeTab.value === 'blogs') {
            searchResults.blogs = response.blogs || []
          } else if (activeTab.value === 'users') {
            searchResults.users = response.users || []
          }
          
          searchResults.total = response.total || 0
        }
      } catch (error) {
        console.error('搜索失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 监听路由变化，更新默认选项卡
    watch(() => route.path, () => {
      if (!searchVisible.value) {
        setDefaultTab()
      }
    })
    
    onMounted(() => {
      setDefaultTab()
    })
    
    return {
      searchVisible,
      searchQuery,
      activeTab,
      loading,
      hasSearched,
      searchResults,
      searchInputRef,
      openSearch,
      closeSearch,
      clearSearchResults,
      onTabChange,
      performSearch,
      handleKeydown,
      handleKeyup,
      handleCompositionStart,
      handleCompositionEnd
    }
  }
}
</script>

<style scoped>
.search-trigger {
  width: 300px;
  margin: 0 20px;
}

.search-input-trigger {
  cursor: pointer;
}

.search-input-trigger :deep(.ant-input) {
  cursor: pointer;
  background-color: #fafafa;
  border-color: #d9d9d9;
}

.search-input-trigger:hover :deep(.ant-input) {
  border-color: #40a9ff;
}

.search-modal :deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  height: 80vh;
}

.search-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

/* 搜索输入区域 */
.search-input-section {
  padding: 32px 40px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background: white;
  border: 2px solid #1890ff;
  border-radius: 12px;
  padding: 12px 20px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
}

.search-input-icon {
  color: #1890ff;
  margin-right: 12px;
  font-size: 20px;
}

.search-main-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 18px;
}

.search-main-input :deep(.ant-input) {
  border: none;
  box-shadow: none;
  padding: 0;
  font-size: 18px;
  background: transparent;
}

.search-main-input :deep(.ant-input:focus) {
  border: none;
  box-shadow: none;
}

.search-button {
  color: #1890ff;
  font-size: 20px;
  cursor: pointer;
  margin-right: 12px;
  transition: color 0.3s;
}

.search-button:hover {
  color: #40a9ff;
}

.search-close-btn {
  color: #8c8c8c;
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s;
}

.search-close-btn:hover {
  color: #1890ff;
}

/* 选项卡区域 */
.search-tabs-section {
  flex: 1;
  overflow: hidden;
  background: white;
}

.search-main-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-main-tabs :deep(.ant-tabs-nav) {
  background: white;
  margin: 0;
  padding: 0 40px;
  border-bottom: 1px solid #f0f0f0;
}

.search-main-tabs :deep(.ant-tabs-tab) {
  padding: 16px 24px;
  font-size: 16px;
  font-weight: 500;
  margin-right: 8px;
}

.search-main-tabs :deep(.ant-tabs-content-holder) {
  flex: 1;
  overflow: hidden;
}

.search-main-tabs :deep(.ant-tabs-tabpane) {
  height: 100%;
  overflow-y: auto;
}

.search-results {
  padding: 32px 40px;
  height: 100%;
  background: white;
  overflow-y: auto;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.no-results {
  text-align: center;
  padding: 80px 20px;
  color: #8c8c8c;
}

.empty-icon {
  font-size: 64px;
  color: #d9d9d9;
  margin-bottom: 20px;
}

.no-results p {
  font-size: 16px;
  margin: 0;
}

.results-list {
  margin-top: 0;
}

.search-tips {
  text-align: center;
  padding: 80px 20px;
  color: #8c8c8c;
  font-size: 16px;
}

.search-tips p {
  margin: 0;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-trigger {
    width: 200px;
    margin: 0 10px;
  }
  
  .search-modal :deep(.ant-modal) {
    width: 95% !important;
    margin: 10px;
  }
  
  .search-header {
    padding: 16px;
  }
  
  .search-results {
    padding: 12px 16px;
  }
}
</style>